package com.xhwl.centiotdata.pollingtrigger.info;

import com.xhwl.centiotdata.handler.info.InfoDeviceFactory;
import com.xhwl.centiotdata.handler.info.InfoDeviceHandler;
import com.xhwl.centiotdata.pojo.dto.haikanginfo.InfoIntegrationPropertiesDTO;
import com.xhwl.centiotdata.pollingtrigger.ScheduleDispatcher;
import com.xhwl.centiotdata.service.integrateconfig.InfoIntegrationConfig;
import com.xhwl.centiotdata.utils.ThreadPoolUtils;
import com.xhwl.common.enums.CategoryEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Author： wuyuhao
 * @Description：
 * @Date 2022/7/30
 */
@Slf4j
@Service
public class InfoDispatcher  implements ScheduleDispatcher {

    @Autowired
    private InfoIntegrationConfig integrationConfig;

    @Override
    public void doOneDayTask() {
        // 信息发布系统设备
        ThreadPoolUtils.executor.execute(this::executePullInfoDevice);
    }

    @Override
    public void doOneHourTask() {
        // 拉取信息发布系统设备设备的在离线状态
        ThreadPoolUtils.executor.execute(this::executePullInfoDeviceStatus);
    }

    public void executePullInfoDevice() {
        // 获取到需要执行拉取信息发布系统设备的项目及配置
        List<InfoIntegrationPropertiesDTO> integrationPropertiesDTOList = integrationConfig.getIntegrationConfig(null);
        integrationPropertiesDTOList.forEach(integrationPropertiesDTO -> {
            try {
                log.info("开始拉取：{}", integrationPropertiesDTO.getProductId());
                InfoDeviceHandler handler = InfoDeviceFactory.getInvokeStrategy(integrationPropertiesDTO.getProductId());
                if (handler == null) {
                    return;
                }
                integrationPropertiesDTO.setDeviceType(47);
                integrationPropertiesDTO.setCategoryEnum(CategoryEnum.INFO_SYSTEM);
                handler.pullInfoDevice(integrationPropertiesDTO);
            } catch (Exception e) {
                log.error("拉取信息发布设备失败，{}", e.getMessage());
            }
        });
    }

    public void executePullInfoDeviceStatus() {
        // 获取到需要执行拉取信息发布系统设备的项目及配置
        integrationConfig.getIntegrationConfig(null).forEach(integrationPropertiesDTO -> {
            try {
                InfoDeviceHandler handler = InfoDeviceFactory.getInvokeStrategy(integrationPropertiesDTO.getProductId());
                if (Objects.isNull(handler)) {
                    return;
                }
                handler.pullDeviceOnlineStatus(integrationPropertiesDTO);
            } catch (Exception e) {
                log.error("拉取信息发布设备状态失败，{}", e.getMessage());
            }
        });
    }

}
